<template>
  <div class="app-container">
    <el-row>
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item label="流程标识" prop="Q_processKey_S_LK">
            <el-input v-model="queryData.Q_processKey_S_LK" placeholder="流程标识" />
          </el-form-item>
          <el-form-item label="流程名称" prop="Q_processName_S_LK">
            <el-input v-model="queryData.Q_processName_S_LK" placeholder="流程名称" />
          </el-form-item>
          <el-form-item label="流程分类" prop="Q_category_S_EQ">
            <el-select v-model="queryData.Q_category_S_EQ" placeholder="流程分类">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in optionOfCategory"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="流程状态" prop="Q_state_S_EQ">
            <el-select v-model="queryData.Q_state_S_EQ" size="small" clearable placeholder="流程状态">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in optionOfState"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="fr p-r-10">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item m-l-10" type="info" round icon="el-icon-refresh" @click="handleClear">
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-row :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['flowable:definition:delete']" v-if="selectionData.length > 0" size="mini" plain type="danger" icon="el-icon-delete" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" />
        </el-row>
        <el-table
          ref="definition_table"
          v-loading="tableLoading"
          row-key="definitionId"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column align="center" label="流程标识" prop="processKey" show-overflow-tooltip />
          <el-table-column align="center" label="流程名称" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button type="text" @click="handleProcessView(scope.row.definitionId)">
                <span>{{ scope.row.processName }}</span>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="流程分类" prop="category" sortable>
            <template slot-scope="scope">
              <el-tag :type="getDictType('category', scope.row.category)" v-text="getDictValue('category', scope.row.category)" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="业务表单">
            <template slot-scope="scope">
              <el-button v-if="scope.row.formId" type="text" @click="handleDetailForm(scope.row)">
                <span>{{ scope.row.formName }}</span>
              </el-button>
              <label v-else>暂无表单</label>
            </template>
          </el-table-column>
          <el-table-column align="center" label="流程版本" width="90">
            <template slot-scope="scope">
              <el-tag size="medium" >v{{ scope.row.version }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="流程状态" prop="suspended" sortable width="105">
            <template slot-scope="scope">
              <el-tag type="success" v-if="!scope.row.suspended">激活</el-tag>
              <el-tag type="warning" v-if="scope.row.suspended">挂起</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="部署时间" prop="deploymentTime" width="180" />
          <el-table-column align="center" label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-dropdown>
                <span class="el-dropdown-link">
                  选项<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-permission="['flowable:definition:publish']">
                    <el-link type="success" icon="el-icon-price-tag" @click="handlePublish(scope.row.processKey)">版本管理</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="!scope.row.suspended" v-permission="['flowable:definition:status']">
                    <el-link type="warning" icon="el-icon-video-pause" @click="handleChangeState(scope.row.definitionId, 'suspended')">挂起</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.suspended" v-permission="['flowable:definition:status']">
                    <el-link type="success" icon="el-icon-video-play" @click="handleChangeState(scope.row.definitionId, 'active')">激活</el-link>
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="['flowable:definition:delete']">
                    <el-link type="danger" icon="el-icon-delete" @click="handleDelete(scope.row.deploymentId)">删除</el-link>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
      </el-card>
    </el-row>

    <!-- 版本管理 -->
    <definition-publish-dialog v-if="openPublishDialog" ref="publishTable" @refresh="getTableData" />
    <!-- 表单展示 -->
    <form-detail-dialog v-if="openFormDetailDialog" ref="detailForm" />
    <!-- 流程图 -->
    <el-drawer :title="processView.title" :visible.sync="processView.open" :modal="false" direction="rtl" size="60%" append-to-body>
      <process-viewer :key="`designer-${processView.index}`" :xml="processView.xmlData" :style="{height: '500px'}" />
    </el-drawer>
  </div>
</template>

<script>
import {
  categoryGroup,
  definitionTable,
  definitionXml,
  definitionChangeState,
  definitionDelete
} from '@/api/tool/workflow'
import ProcessViewer from '@/components/ProcessViewer'
import DefinitionPublishDialog from './table/publish'
import FormDetailDialog from '@/views/tool/flowable/form/detail'

export default {
  components: {
    ProcessViewer,
    DefinitionPublishDialog,
    FormDetailDialog
  },
  data() {
    return {
      showSearch: true,
      queryData: {
        Q_processKey_S_LK: undefined,
        Q_processName_S_LK: undefined,
        Q_category_S_EQ: undefined,
        Q_state_S_EQ: undefined
      },
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectionData: [],
      optionOfCategory: [],
      optionOfState: [],
      openPublishDialog: false,
      openFormDetailDialog: false,
      processView: {
        title: '',
        open: false,
        index: undefined,
        xmlData: '',
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      // 加载下拉菜单
      this.getDictData()
      this.getTableData()
    },
    getDictData() {
      categoryGroup().then(response => {
        this.optionOfCategory = response
      }).catch(e => {})
      this.$dictGroup('bpm_process_instance_status').then(response => {
        this.optionOfState = response
      }).catch(e => {})
    },
    getDictType(property, value) {
      if ('category' === property) {
        return this.$api.getDictElement(this.optionOfCategory, value)[0]
      } else if ('state' === property) {
        return this.$api.getDictElement(this.optionOfState, value)[0]
      }
    },
    getDictValue(property, value) {
      if ('category' === property) {
        return this.$api.getDictElement(this.optionOfCategory, value)[1]
      } else if ('state' === property) {
        return this.$api.getDictElement(this.optionOfState, value)[1]
      }
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      definitionTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.definition_table.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handleDetailForm(row) {
      this.openFormDetailDialog = true
      this.$nextTick(() => {
        this.$refs.detailForm.init(row.formContent)
      })
    },
    handleProcessView(definitionId) {
      this.processView.title = '流程图'
      this.processView.index = definitionId
      definitionXml(definitionId).then(response => {
        this.processView.xmlData = response.param
      })
      this.processView.open = true
    },
    handlePublish(processKey) {
      this.openPublishDialog = true
      this.$nextTick(() => {
        this.$refs.publishTable.init(processKey)
      })
    },
    handleChangeState(definitionId, state) {
      this.tableLoading = true
      definitionChangeState({
        definitionId: definitionId,
        state: state
      }).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.getTableData()
      }).finally(() => this.tableLoading = false)
    },
    handleDelete(deploymentId) {
      const ids = this.selectionData.map(function(model, index) {
        return model.deploymentId
      }).join(',')

      deploymentId = deploymentId || ids
      if (!deploymentId || deploymentId.length === 1) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选流程定义?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        definitionDelete({ ids: deploymentId }).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess('删除成功!')
        })
      })
    }
  }
}
</script>
